package com.wanxs.mall.auth.controller;


import com.alibaba.fastjson.JSON;
import com.wanxs.mall.auth.feign.MemberFeginService;
import com.wanxs.mall.auth.vo.SocialUser;
import com.wanxs.mall.common.constant.AuthConstant;
import com.wanxs.mall.common.utils.HttpUtils;
import com.wanxs.mall.common.utils.Result;
import com.wanxs.mall.common.vo.MemberVO;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class OAuth2Controller {

    @Autowired
    private MemberFeginService memberFeginService;

    @RequestMapping("/oauth2/gitee/success")
    public String weiboOAuth(@RequestParam("code") String code
            , HttpSession session, HttpServletResponse response) throws Exception {
        System.out.println("code = " + code);
        Map<String,String> body = new HashMap<>();
        body.put("client_id","f75bde7133180fb304a8ef3db6bc322b6a53931c92362a121e5896a487e94c60");
        body.put("client_secret","ad5fcd905f660ae795eda59b7fb545430b402acfbf0a19ebd0be3b59e3e3e0cd");
        body.put("grant_type","authorization_code");
        body.put("redirect_uri", "http://auth.wanxs.com/oauth2/gitee/success");
        body.put("code",code);
        // 根据Code获取对应的Token信息
        HttpResponse post = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", new HashMap<>(), new HashMap<>(), body);
        int statusCode = post.getStatusLine().getStatusCode();
        if(statusCode != 200){
            // 说明获取Token失败,就调回到登录页面
            return "redirect:http://auth.wanxs.com/login.html";
        }
        // 说明获取Token信息成功
        String json = EntityUtils.toString(post.getEntity());
        SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
        Result r = memberFeginService.socialLogin(socialUser);
        if(r.getCode() != 0){
            // 登录错误
            return "redirect:http://auth.wanxs.com/login.html";
        }
        String entityJson = (String) r.getData();
        MemberVO memberVO = JSON.parseObject(entityJson, MemberVO.class);
        session.setAttribute(AuthConstant.AUTH_SESSION_REDIS,memberVO);
        // 注册成功就需要调整到商城的首页
        return "redirect:http://mall.wanxs.com/home";
    }
}
